﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Text.RegularExpressions;
using Jzy.Workflow.Flow;

namespace Jzy.Workflow.Html
{
    public class HtmlAnalyzer
    {
        public static XElement GetHtml(System.Web.HttpPostedFile file)
        {
            StreamReader sdr = new StreamReader(file.InputStream, Encoding.Default);
            string tmp = sdr.ReadToEnd();

            XElement html = new XElement(ElementItem.Html);


            XElement head = new XElement(ElementItem.Head);

            Regex style = new Regex(@"<style(.|\n)*</style>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            foreach (Match match in style.Matches(tmp))
            {
                head.Value += match.Value;
            }

            Regex script = new Regex(@"<\s*script(.|\n)*<\s*/\s*script\s*>", RegexOptions.IgnoreCase);

            foreach (Match match in script.Matches(tmp))
            {
                head.Value += match.Value;
            }


            html.Add(head);

            XElement body = new XElement(ElementItem.Body);
            Regex form = new Regex(@"(<\s*form[^>]*?>)((.|\n)*?)(<\s*/\s*form\s*>)", RegexOptions.IgnoreCase);

            body.Value = form.Match(tmp).Groups[2].Value;

            if (body.Value.Trim() == "")//表单里可能没有form
            {
                form = new Regex(@"(<\s*body[^>]*?>)((.|\n)*?)(<\s*/\s*body\s*>)", RegexOptions.IgnoreCase);
                body.Value = form.Match(tmp).Groups[2].Value;
            }

            html.Add(body);




            XElement dataField = new XElement(ElementItem.DataFields);

            int index = 0;
            StringBuilder sbBodyValue = new StringBuilder(body.Value);

            AddDataFields(sbBodyValue, dataField, "input", ref index);
            AddDataFields(sbBodyValue, dataField, "textarea", ref index);
            AddDataFields(sbBodyValue, dataField, "select", ref  index);

            body.Value = sbBodyValue.ToString();

            html.Add(dataField);

            return html;
        }


        /// <summary>
        /// 对ID或Name重名不加判断
        /// </summary>
        /// <param name="src"></param>
        /// <param name="target"></param>
        /// <param name="tagName"></param>
        /// <param name="ctlIndex"></param>
        private static void AddDataFields(StringBuilder src, XElement target, string tagName, ref int ctlIndex)
        {

            Regex input = new Regex(@"<\s*" + tagName + @"[^>]*?>", RegexOptions.IgnoreCase);

            foreach (Match result in input.Matches(src.ToString()))
            {
                string str = result.Value;//一个控件字符串


                if (str.Contains("button") || str.Contains("submit") || str.Contains("file"))
                {
                    continue;
                }

                Regex ctlName = new Regex("name\\s*=['\"]?(\\s*\\w*\\s*)['\" >]", RegexOptions.IgnoreCase);
                Regex ctlType = new Regex("type\\s*=['\"]?(\\s*\\w*\\s*)['\" >]", RegexOptions.IgnoreCase);

                string fieldName = ctlName.Match(str).Groups[1].Value;
                string fieldType = ctlType.Match(str).Groups[1].Value.ToLower();
                if (tagName == "textarea" || tagName == "select")
                {
                    fieldType = tagName;
                }
                else
                {
                    if (fieldType == "")
                    {
                        fieldType = "text";
                    }
                }

                if (fieldName.Trim() != "")
                {
                    XElement field = new XElement(fieldName);
                    //加type
                    field.SetAttributeValue(BasicSetItem.Type, fieldType);
                    target.Add(field);
                }
                else
                {
                    int index = str.IndexOf(tagName) + tagName.Length;
                    str = str.Insert(index, " name=\"" + tagName.ToLower() + "_" + ctlIndex + "\" ");

                    XElement field = new XElement(tagName.ToLower() + "_" + ctlIndex);
                    field.SetAttributeValue(BasicSetItem.Type, fieldType);
                    target.Add(field);

                    ctlIndex++;
                    src.Replace(result.Value, str);
                }


                //让ID和Name同步

                Regex ctlID = new Regex("id\\s*=['\"]?(\\s*\\w*\\s*)['\" >]", RegexOptions.IgnoreCase);

                string fieldID = ctlID.Match(str).Groups[1].Value;
                if (fieldID.Trim() != "")
                {
                    if (fieldID != fieldName)//如果ID和Name不等
                    {
                        string tmp = str.Replace(ctlID.Match(str).Value, "id=\"" + fieldName + "\"");
                        src.Replace(str, tmp);
                    }
                }
                else
                {
                    int index = str.IndexOf(tagName) + tagName.Length;
                    string tmp = str.Insert(index, " id=\"" + fieldName + "\" ");
                    src.Replace(str, tmp);
                }
            }

        }
    }
}
